package com.iyue.util.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 
 * 
 * @author 孙晓晔
 * @version $Id: ImageCode.java,v 1.1 2010/10/14 17:07:15 fresh Exp $
 */
public final class ImageCode {
	public Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	public BufferedImage creatImage(String vcode) {
		int width = 48, height = 15;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Graphics graphics = image.getGraphics();
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));

		for (int i = 0; i < 4; i++) {
			String rand = vcode.substring(i, i + 1);
			graphics.setColor(new Color(0, 0, 0));
			graphics.drawString(rand, 11 * i + 1, 15);
		}
		graphics.dispose();

		return image;
	}

	protected BufferedImage creatImage3D(int number, int max) {
		// 在内存中创建图象
		int width = 60, height = 10;
		int x = number * width / max;
		BufferedImage image = new BufferedImage(x, height,
				BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// g.fillRect(0, 0, width, height);

		g.setColor(this.getRandColor(100, 200));
		g.draw3DRect(0, 0, x, height, true);
		g.fill3DRect(0, 0, x, height, true);
		// 图象生效
		g.dispose();

		return image;
	}
	/**
	 * 创建白底的宽widht，高height的图像
	 * 
	 * @param width
	 * @param height
	 * @return
	 */
	public BufferedImage creatImage(int width, int height) {
		// 在内存中创建图象
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics graphics = image.getGraphics();

		// 设定背景色
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, width, height);

		return image;
	}
}
